
package com.means.polymerize.assembly.filter;

import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Request Body 缓存 Filter，实现它的可重复读取
 *
 * @author xuhaifeng
 * @date 2021.05.05
 */
public class CacheRequestBodyFilter extends OncePerRequestFilter {
    private static boolean isJsonRequest(ServletRequest request) {
        return StrUtil.startWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE);
    }

    @Override
    @SneakyThrows(value = {IOException.class, ServletException.class})
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
        filterChain.doFilter(new CacheRequestBodyWrapper(request), response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        /* 只处理 json 请求内容 */
        return !isJsonRequest(request);
    }
}
